<?php
namespace control;
/*
*稽核统计类
*/

class checkStatisticsClass extends adIndexClass
{
    private const page = 'checkStatistics';
    private const table = 'inspection';
    private const tableMx = 'inspection_detail';
    private const title = '稽核统计';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'target'          => [
                        'name'  => '受稽核对象',
                        'width' => 300,
                    ],
                    'inspectionTotal' => [
                        'name'  => "稽核项数",
                        'width' => 200,
                    ],
                    'inconformity'  => [
                        'name'  => "不符合项数",
                        'width' => 200,
                    ],
                    'inconformityRate'         => [
                        'name'  => '不符合率',
                        'width' => 200,
                    ],
                    'rectificationTotal'          => [
                        'name'  => '通知整改项数',
                        'width' => 200,
                    ],
                    'completion'          => [
                        'name'  => '整改完成项数',
                        'width' => 200,
                    ],
                    'completionRate'          => [
                        'name'  => '整改完成率',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    '稽核日期'   => text(array("name" => "recordDate", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "受稽核对象" => text(array("name" => "target_name")),
                    "稽核类别"     => select(array("name" => "type", "option" => explode('，',para('inspectionType')))),
                ],
                [
                    '稽核级别' => select(array("name" => "level", "option" => [1=>'内部',2=>'外部']))
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "target_name" => $this->post('target_name'),//受稽核对象
        );
        //全等查询数组
        $equal = array(
            "state" => '已通过',
            "level" => $this->post('level'),//稽核级别
            "type" => $this->post('type'),//稽核类别
        );
        $and = "";
        if ($this->post('recordDate')) {
            $and .= self::timeComparison($this->post('recordDate'), field: 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'target',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::table,
            "where" => '1=1 and target is not null'.$where." group by target ",
            "field" => "target",
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['target']),
            );
            $liButton[] = $this->dominate($dominate);
            $inspectionTotal = find(array('table' => " inspection_detail as a left join inspection as b on a.orderId = b.id ", 'single' => " b.target = '$array[target]' and b.state = '已通过' ", 'field' => " ifnull(count(a.id),0) as total "));
            $inconformity = find(array('table' => " inspection_detail as a left join inspection as b on a.orderId = b.id ", 'single' => " b.target = '$array[target]' and b.state = '已通过' and a.results = 2 ", 'field' => " ifnull(count(a.id),0) as total "));
            $inconformityRate = $inconformity['total']==0?0:round($inconformity['total']/$inspectionTotal['total'],2)*100;

            $rectificationTotal = find(array('table' => " rectification_detail as a left join rectification as b on a.orderId = b.id ", 'single' => " b.target = '$array[target]' and b.state = '已通过' ", 'field' => " ifnull(count(a.id),0) as total "));
            $completion = find(array('table' => " rectification_detail as a left join rectification as b on a.orderId = b.id ", 'single' => " b.target = '$array[target]' and b.state = '已通过' and a.completion = 1 ", 'field' => " ifnull(count(a.id),0) as total "));
            $completionRate = $completion['total']==0?0:round($completion['total']/$rectificationTotal['total'],2)*100;
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "target":
                        $row[] = checkPlanClass::findDepartment((array)explode(',',$array['target']));
                        break;
                    case "inspectionTotal":
                        $row[] = $inspectionTotal['total'];
                        break;
                    case "inconformity":
                        $row[] = $inconformity['total'];
                        break;
                    case "inconformityRate":
                        $row[] = $inconformityRate.'%';
                        break;
                    case "rectificationTotal":
                        $row[] = $rectificationTotal['total'];
                        break;
                    case "completion":
                        $row[] = $completion['total'];
                        break;
                    case "completionRate":
                        $row[] = $completionRate.'%';
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            $sql   = $_SESSION[self::page]['sql'];
            $result   = sqlFind($sql);
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $inspectionTotal = find(array('table' => " inspection_detail as a left join inspection as b on a.orderId = b.id ", 'single' => " b.target = '$array[target]' and b.state = '已通过' ", 'field' => " ifnull(count(a.id),0) as total "));
                $inconformity = find(array('table' => " inspection_detail as a left join inspection as b on a.orderId = b.id ", 'single' => " b.target = '$array[target]' and b.state = '已通过' and a.results = 2 ", 'field' => " ifnull(count(a.id),0) as total "));
                $inconformityRate = $inconformity['total']==0?0:round($inconformity['total']/$inspectionTotal['total'],2)*100;

                $rectificationTotal = find(array('table' => " rectification_detail as a left join rectification as b on a.orderId = b.id ", 'single' => " b.target = '$array[target]' and b.state = '已通过' ", 'field' => " ifnull(count(a.id),0) as total "));
                $completion = find(array('table' => " rectification_detail as a left join rectification as b on a.orderId = b.id ", 'single' => " b.target = '$array[target]' and b.state = '已通过' and a.completion = 1 ", 'field' => " ifnull(count(a.id),0) as total "));
                $completionRate = $completion['total']==0?0:round($completion['total']/$rectificationTotal['total'],2)*100;
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '受稽核对象'=>checkPlanClass::findDepartment((array)explode(',',$array['target'])),
                            '稽核项数'=> $inspectionTotal['total'],
                            '不符合项数'=>$inconformity['total'],
                            '不符合率'=>$inconformityRate.'%',
                            '通知整改项数'=>$rectificationTotal['total'],
                            '整改完成项数'=>$completion['total'],
                            '整改完成率'=>$completionRate.'%',
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了稽核统计";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "稽核统计.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }
    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'受稽核对象',
                    'aliasName'=>'受稽核对象',
                ],
                [
                    'columnName'=>'稽核项数',
                    'aliasName'=>'稽核项数',
                ],
                [
                    'columnName'=>'不符合项数',
                    'aliasName'=>'不符合项数',
                ],
                [
                    'columnName'=>'不符合率',
                    'aliasName'=>'不符合率',
                ],
                [
                    'columnName'=>'通知整改项数',
                    'aliasName'=>'通知整改项数',
                ],
                [
                    'columnName'=>'整改完成项数',
                    'aliasName'=>'整改完成项数',
                ],
                [
                    'columnName'=>'整改完成率',
                    'aliasName'=>'整改完成率',
                ],
            ]
        };
    }
}

